const axios = require('axios')

const FormData = require('form-data')

const {generateRandomString, unicodeToUtf8} = require('../utils/fun')


const BaseUrl = "https://h5.uu89.com"

function createService() {
    // 创建一个 axios 实例
    const service = axios.create()

    // HTTP request 拦截器
    service.interceptors.request.use(
        config => config,
        error => {
            // 失败
            return Promise.reject(error);
        }
    );

    // HTTP response 拦截器
    service.interceptors.response.use(
        response => {
                if(response.status != 200){
                    console.log(response.data)
                }
                if(response.config?.original){
                    return response
                }
                return response.data
        },
        error => {
            if (error.response) {
                console.log("请求已发出，但服务器返回状态码不在 2xx 范围内")
                console.error('Response Error:', error.response.data);
                console.error('Status Code:', error.response.status);
                console.error('Headers:', error.response.headers);
            } else if (error.request) {
                console.log("请求已发出，但没有收到响应")
                console.error('Request Error:', error.message);
            } else {
                //
                console.error('发送请求时发生错误，无法触及服务器:', error.message);
            }
            return Promise.reject(error.response && error.response.data ? error.response.data : null)
        }
    )
    return service
}


/**
 * @description 创建请求方法
 * @param {Object} service axios 实例
 */
function createRequest(service) {
    return function (config) {
        let data = config.data || {}
            , headers = {
            "X-Requested-With": "com.cecy.mobile.rxhwtjfl.toutiao",
            'User-Agent': "Mozilla/5.0 (Linux; Android 9; PCLM10 Build/PQ3A.190705.11271837; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/91.0.4472.114 Mobile Safari/537.36",
            "gr-h5-version": "1.0.1",
            "Referer": BaseUrl + "/h5/sdk/index.html",
            "Origin": BaseUrl
        }
        if (config.hasOwnProperty('formData')) {
            data = new FormData()
            data._boundary = "----WebKitFormBoundary" + generateRandomString(16)
            for (let i in config.formData) {
                data.append(i, config.formData[i])
            }
            headers = Object.assign(headers, data.getHeaders())
        }
        const configDefault = {
            headers: Object.assign(
                headers,
                config.header
            ),
            timeout: 3000,
            baseURL: BaseUrl,
            data: data
        }
        const option = Object.assign(configDefault, config)
        return service(option)
    }
}

const request = createRequest(createService())

module.exports = {
    request
}